﻿/****************
 * Copyright 2016 Brian Tabone
 * Licensed under the Apache 2.0 License
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * PropertiesController.cs
 * REST endpoint for SCADA (supervisory control and data acquisition) get/set properties messages
 * 8/20/2016
 */

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http.Formatting;
using System.Web.Http;
using IAO.Common.Network.EventArgs;
using IAO.Common.Network.MessageImplementations.SCADA;

namespace IAO.Common.Network.MessageControllers
{
    public class PropertiesController : ApiController
    {
        public delegate List<PropertyMessage> GetPropertiesEventHandler(object sender, System.EventArgs e);

        public delegate void SetPropertiesEventHandler(object sender, SetPropertyEventArgs args);

        public static event GetPropertiesEventHandler GetPropertiesEvent;
        public static event SetPropertiesEventHandler SetPropertiesEvent;

        /// <summary>
        ///     Get api/properties
        /// </summary>
        /// <returns></returns>
        public IEnumerable<PropertyMessage> Get()
        {
            return GetPropertiesEvent?.Invoke(this, null);
        }

        public PropertyMessage Get(int id)
        {
            return GetPropertiesEvent?.Invoke(this, null).Find(pr => pr.Id == id);
        }

        [HttpPost]
        [ActionName("properties")]
        public HttpStatusCode Post(FormDataCollection form)
        {
            var id = int.Parse(form["id"]);
            var value = form["value"];

            if (SetPropertiesEvent != null)
            {
                try
                {
                    SetPropertiesEvent(this, new SetPropertyEventArgs {PropertyID = id, NewValue = value});
                    return HttpStatusCode.OK;
                }
                catch (Exception)
                {
                    //TODO log exception
                    return HttpStatusCode.NotModified;
                }
            }

            return HttpStatusCode.NotImplemented;
        }
    }
}